<template>
  <el-dialog :title="$t('msg.excel.title')" :model-value="modelValue" >
    <el-input v-model="excelName" :placeholder="$t('msg.excel.placeholder')"></el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">{{$t('msg.excel.close')}}</el-button>
        <el-button type="primary" @click="onConfirm" :loading="loading">{{$t('msg.excel.confirm')}}</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { watchSwitchLang } from '../../../../utils/i18n'
import { userExport } from '../../../../api/user'
import { USER_RELATTONS } from '../../../../utils/Export2ExcelConstants'
import { exportJson2Excel } from '../../../../utils/excel'
import { dateFilter } from '../../../../filters'
defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})
const i18n = useI18n()
let exportDefaultName = i18n.t('msg.excel.defaultName')
const excelName = ref('')
watchSwitchLang(() => {
  exportDefaultName = i18n.t('msg.excel.defaultName')
})
excelName.value = exportDefaultName
const emits = defineEmits(['update:modelValue'])
/**
 * 关闭事件
 */
const closed = () => {
  emits('update:modelValue', false)
}
// 点击确定
const loading = ref(false)

const onConfirm = async () => {
  loading.value = true
  // 数据
  const allUser = await userExport()
  // console.log(allUser)
  const data = formatJson(USER_RELATTONS, allUser)
  exportJson2Excel(Object.keys(USER_RELATTONS), data, excelName.value !== '' ? excelName.value : exportDefaultName, undefined, undefined, true, 'xlsx')
  // console.log(data)
  closed()
}
// 当我们使用exportJson2Excel 的时候,我们传递的数据,它必须是一个二维数组
const formatJson = (headers: any, rows: any) => {
  return rows.map((item: any) => {
    return Object.keys(headers).map(key => {
      // 角色需要进行特殊处理
      // if (headers[key] === 'role') {
      //   const roles = item[headers[key]]
      //   return JSON.stringify(roles.map((role: any) => role.name))
      // }

      // 时间
      if (headers[key] === 'createAt') {
        return dateFilter(item[headers[key]])
      }
      return item[headers[key]]
    })
  })
}
</script>
<style scoped lang="scss"></style>
